var _gl = require('opengl');
var _MeshNode = require('drawable/meshnode.js');
var _createMesh = require('glcore/meshbuffer.js').createMesh;
var _inherit = require('core/inherit.js');

var _geometry = require('core/glm.js');

var MatrixDirty = _MeshNode.prototype.FlagTouchMatrix | _MeshNode.prototype.FlagMatrix;

function Text(material, font) {
    _MeshNode.call(this, null, material);

    this.font = font;
    this.mText = '';
    this.mVisiable = false;
    this.setSize(0, font.height);
}
_inherit(Text, _MeshNode);
Text.prototype.setText = function (text) {
    if (typeof text != 'string') {
        text = text + '';
    }
    if (text != this.mText) {
        this.mText = text;
        if (!this.mText || this.mText.length == 0) {
            this.mVisiable = false;
        } else {
            this.mVisiable = true;
            this.createMesh();
            this.updateOffset();
            this.addFlag(MatrixDirty);
        }
    }
};
Text.prototype.createMesh = function () {
    var len = this.mText.length;
    var b = this.mBuffer = _createMesh('p2t2', len * 6, _gl.TRIANGLES);
    var element = new Float32Array(b.adapter().buffer());
    var height = this.font.height;

    var twidths = new Float32Array(len * 2);
    var glyphs = new Float32Array(len * 16);
    var point = new Float32Array(4);

    this.font.load(this.mText);
    this.font.measure(this.mText, twidths);// [advance,kerning]
    this.font.glyphs_rect(this.mText, glyphs);// [{x1,y1,s0,t0},{x1,y2,s0,t1},{x2,y1,s1,t0},{x2,y2,s1,t1}]

    var x = 0;
    var y = -this.font.ascender;

    var gindex = 0;
    var windex = 0;
    var pindex = 0;
    var order = [0, 1, 2, 5];
    for (var i = 0; i < len; i++) {
        x += twidths[windex + 1];

        for (var rect = 0; rect < 4; rect++) {
            glyphs.get(point, rect * 4 + gindex);
            point[0] += x;
            point[1] += y;
            element.set(point);
            b.push(pindex + order[rect]);
        }
        b.copy(pindex + 2, pindex + 3, 1);
        b.copy(pindex + 1, pindex + 4, 1);

        x += twidths[windex];
        gindex += 16;
        windex += 2;
        pindex += 6;
    }

    this.setSize(x, height);
    this.setCenter(0, height);
    b.upload();
};
Text.prototype.draw = function (context) {
    if (!this.mVisiable) {
        return;
    }
    _gl.blendFunc(_gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA);
    this.updateMatrix();
    context.render(this, this.mBuffer, this.mMaterial);
    _gl.blendFunc(_gl.ONE, _gl.ONE_MINUS_SRC_ALPHA);
};

module.exports = Text;